package Demo.Controller;

import Demo.Pojo.Book;
import Demo.Uti.DatabaseUtil;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;


import java.sql.*;
import java.util.Optional;

public class BookManagementUI {

    //数据库jdbc连接
    private Connection connection;
    //booksTable：用于显示书籍列表的 TableView
    private TableView<Book> booksTable;
    //booksData：一个可观察的列表（ObservableList），存储 Book 对象,为book他变了提供数据
    private ObservableList<Book> booksData = FXCollections.observableArrayList();


    public BookManagementUI(Connection connection) {
        this.connection = connection;
    }

    public void show() {

        // 创建一个新的Stage作为子窗口
        Stage bookStage = new Stage();
        bookStage.initModality(Modality.APPLICATION_MODAL);//初始舞台风格
        bookStage.setTitle("图书管理系统用户操作页面");

        // 创建网格面板,布局
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));

        // 初始化场景
        Scene scene = new Scene(grid, 600, 500);
        bookStage.setScene(scene);
        bookStage.show();

        // 创建表单字段
        TextField idTextField = new TextField();
        TextField titleTextField = new TextField();
        TextField authorTextField = new TextField();
        TextField yearTextField = new TextField();
        TextField isbnTextField = new TextField();

        // 创建表格
        booksTable = new TableView<>();
        booksTable.setEditable(true);
        booksTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        // 加载书籍数据
        loadBooks();

        // 创建增删改查按钮，并添加到水平盒子中
        Button addButton = new Button("添加");
        Button removeButton = new Button("移除");

        HBox buttonBox = new HBox(10); // 创建水平盒子来放置按钮
        buttonBox.getChildren().addAll(addButton, removeButton);

        // 将组件添加到网格面板
        grid.add(new Label("ID:"), 0, 0);
        grid.add(idTextField, 1, 0, 1, 1); // 占据一行两列
        grid.add(new Label("Title:"), 0, 1);
        grid.add(titleTextField, 1, 1, 2, 1); // 占据一行两列
        grid.add(new Label("Author:"), 0, 2);
        grid.add(authorTextField, 1, 2, 2, 1); // 占据一行两列
        grid.add(new Label("Year:"), 0, 3);
        grid.add(yearTextField, 1, 3, 1, 1); // 占据一行一列
        grid.add(new Label("ISBN:"), 2, 3);
        grid.add(isbnTextField, 3, 3, 1, 1); // 占据一行一列
        grid.add(booksTable, 0, 4, 4, 5); // 占据四行五列
        grid.add(buttonBox, 0, 9, 4, 1); // 占据一行四列

        // 按钮事件处理
        addButton.setOnAction(e -> addBook(idTextField, titleTextField, authorTextField, yearTextField, isbnTextField));
        removeButton.setOnAction(e -> removeBook());

    }

    private void addBook(TextField idField, TextField titleField, TextField authorField, TextField yearField, TextField isbnField) {
        // 插入新书籍到数据库
        String idText = idField.getText();
        String title = titleField.getText();
        String author = authorField.getText();
        String yearText = yearField.getText();
        String isbn = isbnField.getText();

        // 确保年份字段输入的是整数
        int year;
        int id;
        try {
            year = Integer.parseInt(yearText);
            id = Integer.parseInt(idText);
        } catch (NumberFormatException e) {
            new Alert(Alert.AlertType.ERROR, "年份应该是一个整数。", ButtonType.OK).show();
            return;
        }

        try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO books (id, title, author, year, isbn) VALUES (?, ?, ?, ?, ?)")) {
            stmt.setInt(1, id);
            stmt.setString(2, title);
            stmt.setString(3, author);
            stmt.setInt(4, year);
            stmt.setString(5, isbn);
            stmt.executeUpdate();

            // 刷新表格数据
            booksData.add(new Book(id, title, author, year, isbn));
            booksTable.setItems(booksData);

            // 清空输入字段
            idField.clear();
            titleField.clear();
            authorField.clear();
            yearField.clear();
            isbnField.clear();

            new Alert(Alert.AlertType.INFORMATION, "书籍添加成功。", ButtonType.OK).show();
        } catch (SQLException ex) {
            ex.printStackTrace();
            // 显示错误信息
            new Alert(Alert.AlertType.ERROR, "添加书籍时出错：" + ex.getMessage(), ButtonType.OK).show();
        }
    }


    private void removeBook() {
        Book selectedBook = booksTable.getSelectionModel().getSelectedItem();
        if (selectedBook != null) {
            String authorToDelete = selectedBook.getAuthor(); // 获取选中书籍的作者

            Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "确定要删除这本书吗？", ButtonType.YES, ButtonType.NO);
            alert.setTitle("确认删除");
//            显示对话框并等待用户的响应。
//            用户响应后，方法返回一个 Optional<ButtonType> 对象，
//            其中可能包含用户点击的按钮类型（ButtonType.YES 或 ButtonType.NO），
            Optional<ButtonType> result = alert.showAndWait();
//            首先检查 Optional 对象是否包含一个值（result.isPresent() 返回 true 表示包含值）。
//            如果包含值，它进一步检查这个值是否等于 ButtonType.YES，这意味着用户点击了“是”按钮。
            if (result.isPresent() && result.get() == ButtonType.YES) {
                try {
                    // 使用书籍的作者来构建删除条件
                    String deleteQuery = "DELETE FROM books WHERE author = '" + authorToDelete + "'";
                    int rowsAffected = connection.createStatement().executeUpdate(deleteQuery);

                    if (rowsAffected > 0) {
                        // 从数据列表中删除书籍
                        booksData.remove(selectedBook);
                        booksTable.setItems(booksData);
                        new Alert(Alert.AlertType.INFORMATION, "书籍删除成功。", ButtonType.OK).show();
                    } else {
                        new Alert(Alert.AlertType.ERROR, "删除书籍失败，未找到匹配的书籍。", ButtonType.OK).show();
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    new Alert(Alert.AlertType.ERROR, "删除书籍时出错：" + ex.getMessage(), ButtonType.OK).show();
                }
            }
        } else {
            new Alert(Alert.AlertType.INFORMATION, "请选择要删除的书籍。", ButtonType.OK).show();
        }
    }


    private void loadBooks() {
        try {
            // 清空已有数据
            booksData.clear();
            // 确保表格列已初始化
            initializeTableColumns();

            // 从数据库加载书籍数据
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM books");

            // 检查是否有数据
            while (rs.next()) {
                int id = rs.getInt("id"); // 确保列名与数据库中的列名匹配
                String title = rs.getString("title");
                String author = rs.getString("author");
                int year = rs.getInt("year");
                String isbn = rs.getString("isbn"); // 确保列名与数据库中的列名匹配

                // 添加书籍到ObservableList
                booksData.add(new Book(id, title, author, year, isbn));
            }

            // 设置TableView的数据源
            booksTable.setItems(booksData);

            rs.close();
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
            new Alert(Alert.AlertType.ERROR, "加载书籍数据时出错：" + ex.getMessage(), ButtonType.OK).show();
        }
    }

    private void initializeTableColumns() {
        // 确保这些列与数据库中的列名和Book类中的属性名匹配
        TableColumn<Book, Integer> idColumn = new TableColumn<>("ID");
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        TableColumn<Book, String> titleColumn = new TableColumn<>("Title");
        titleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));
        TableColumn<Book, String> authorColumn = new TableColumn<>("Author");
        authorColumn.setCellValueFactory(new PropertyValueFactory<>("author"));
        TableColumn<Book, Integer> yearColumn = new TableColumn<>("Year");
        yearColumn.setCellValueFactory(new PropertyValueFactory<>("year"));
        TableColumn<Book, String> isbnColumn = new TableColumn<>("ISBN");
        isbnColumn.setCellValueFactory(new PropertyValueFactory<>("isbn"));

        // 添加列到表格
        booksTable.getColumns().setAll(idColumn, titleColumn, authorColumn, yearColumn, isbnColumn);
    }


    // 主方法，用于启动应用程序
    public static void main(String[] args) throws SQLException {
        // 获取数据库连接
        Connection connection = DatabaseUtil.getConnection();

        // 创建并显示图书管理界面
        BookManagementUI bookManagementUI = new BookManagementUI(connection);
        bookManagementUI.show();
    }
}